package com.web.base.auth.dao;

import com.blue.jdbc.BaseDao;
import com.web.base.auth.model.MenuButton;
import com.web.base.auth.model.RoleMenuButton;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色－按钮数据库访问
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年04月15日
 */
@Repository
public class RoleMenuButtonDao extends BaseDao<RoleMenuButton>
{
	public RoleMenuButtonDao()
	{
	}
	
	@Override
	protected void query(StringBuilder sql, RoleMenuButton param)
	{
		if (param != null)
		{
			if (param.getRoleId() != null)
				sql.append(" and a.role_id=:roleId");
			
			if (param.getButtonId() != null)
				sql.append(" and a.button_id=:buttonId");
		}
	}
	
	@Override
	protected StringBuilder select()
	{
		StringBuilder sql = new StringBuilder(32);
		sql.append("select a.*, mb.code from auth_role_menu_button a");
		sql.append(" left join auth_menu_button mb on mb.id=a.button_id");
		sql.append(" where 1=1");
		return sql;
	}

	public List<MenuButton> listSelect(Integer roleId, Integer appId)
	{
		Map<String, Object> param = new HashMap<>();
		param.put("roleId", roleId);
		param.put("appId", appId);
		String sql = "select mb.id, mb.menu_id, mb.name, mb.code, isnull(rmb.role_id) selected from auth_menu_button mb"
				+ " inner join auth_menu m on m.id=mb.menu_id"
				+ " left join (select * from auth_role_menu_button where role_id=:roleId) rmb on rmb.button_id=mb.id"
				+ " where mb.state=0 and m.id=mb.menu_id and m.app_id=:appId";
		return jdbcObjectTemplate.list(MenuButton.class, sql, param);
	}

	public void deleteByMenu(Integer menuId)
	{
		String sql = "delete from auth_role_menu_button where button_id in (select id from auth_menu_button where menu_id=?)";
		jdbcTemplate.update(sql, menuId);
	}
	
}
